package com.power.sifa.approve.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollectionUtil;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.domain.ResponseDTO;
import com.plf.common.utils.ExcelUtil;
import com.plf.common.utils.SpringHolder;
import com.plf.common.utils.StringUtil;
import com.plf.core.common.file.FileController;
import com.power.sifa.approve.api.IApl_applicantFeign;
import com.power.sifa.approve.model.Apl_applicant;
import com.power.sifa.approve.model.Apl_thirdper;
import com.power.sifa.approve.model.pageInfo.Apl_applicantPageInfo;
import com.power.sifa.approve.service.Apl_applicantService;
import com.power.sifa.approve.service.Apl_thirdperService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;



/**
 *   申请人控制器
 */

@Slf4j
//@PowerLog
@RestController
@Api(value = "Apl_applicantController",tags={"申请人"})
public class Apl_applicantController implements IApl_applicantFeign {

    @Resource
    private Apl_applicantService apl_applicantService;

    @Resource
    private Apl_thirdperService apl_thirdperService;


    @Override
    @ApiOperation("查询申请人分页列表")
    @SaCheckPermission("apl_applicant_list")
    public ResponseDTO list(Apl_applicantPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo参数不能为空");
        Page<Apl_applicant> page = this.apl_applicantService.findAll(pageInfo);
        List list = new ArrayList();
        if (!page.isEmpty()) {
            for (Apl_applicant apl_applicant : page) {
                apl_applicant.geneText();
                list.add(apl_applicant);
            }
        }
        PageDataResponse p = new PageDataResponse(list, page.getTotalElements(), page.getSize(), pageInfo.getPageNumber()<=1 ? 1 : pageInfo.getPageNumber());
        return ResponseDTO.succData(p);
    }

    @Override
    @ApiOperation("查看申请人")
    @SaCheckPermission("apl_applicant_view")
    public ResponseDTO view(String id) {
        Assert.notNull(id, "id不能为空");
        Apl_applicant apl_applicant  = apl_applicantService.getById(id);
        if (apl_applicant != null) {
            apl_applicant.geneText();
        }
        return ResponseDTO.succData(apl_applicant);
    }

    @Override
    @ApiOperation("删除申请人")
    @SaCheckPermission("apl_applicant_del")
    public ResponseDTO delete(String id) {
        Assert.notNull(id, "id不能为空");
        apl_applicantService.removeById(id);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation("保存或修改申请人")
    @SaCheckPermission("apl_applicant_save")
    public ResponseDTO save(Apl_applicant apl_applicant) {
        Assert.notNull(apl_applicant, "apl_applicant不能为空");
        apl_applicantService.saveOrUpdate(apl_applicant);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation(value="批量删除申请人")
    @SaCheckPermission("apl_applicant_del")
    public ResponseDTO batchDel(String ids) {
        Assert.isTrue(StringUtils.hasText(ids), "ids不能为空");
        List<Integer> list = Arrays.asList(ids.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        apl_applicantService.removeByIds(list);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation(value="导出excel")
    @SaCheckPermission("apl_applicant_list")
    public void output(HttpServletResponse response, Apl_applicantPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo不能为空");
        String title = "申请人";
        String[] heads = {"applyid+nanoid","applyid","申请人类型","名称","证件类型","证件号","联系地址","联系电话","邮政编码","法定代表人或主要负责人",
                "工作单位","民族","性别","职务","是否代表人","排序","代理人id","出生年月","社会统一信用代码","附件id","提交时间","案件号","状态","申请号","被申请人"};
        String[] fields = {"id","applyid","type","name","cardtype","cardno","addr","tel","postcode","manager","unit",
                "nation","gender","job","isrepr","sortnum","agentid","birthym","cornumber","attachid","subtime",
                "acceptcode","status","applyname","targetname"};

        Page<Apl_applicant> page = this.apl_applicantService.findAll(pageInfo);
        ExcelUtil.exportXls(title, heads, fields, page.getContent(), response);
    }

    @Override
    @ApiOperation(value="导出excel模板")
    public void exportExcelTemplate(HttpServletResponse response) {
        String title = "申请人";
        //id自增或list从表可自行删除，需与导入项一致
        String[] heads = {"applyid+nanoid","applyid","申请人类型","名称","证件类型","证件号","联系地址","联系电话","邮政编码","法定代表人或主要负责人","工作单位","民族","性别","职务","是否代表人","排序","代理人id","出生年月","社会统一信用代码","附件id","提交时间","案件号","状态","申请号","被申请人"};
        ExcelUtil.exportXls(title, heads, null, null, response);
    }

	@Override
	@ApiOperation(value="导入excel")
	public ResponseDTO importExcel(MultipartFile file) throws IOException {
        Assert.notNull(file, "file不能为空");
        //id自增或list从表可自行删除，需与下载的模板中导入项一致
        String[] fields = {"id","applyid","type","name","cardtype","cardno","addr","tel","postcode","manager","unit","nation","gender","job","isrepr","sortnum","agentid","birthym","cornumber","attachid","subtime","acceptcode","status","applyname","targetname"};
        List<Apl_applicant> list = (List<Apl_applicant>)ExcelUtil.Import(fields, file, Apl_applicant.class);
        if(!CollectionUtils.isEmpty(list)) {
            this.apl_applicantService.saveAll(list);
        }
        return ResponseDTO.succ();
	}

    @Override
    public ResponseDTO getAppperAndThiperByApplyid(String applyid) {
        return ResponseDTO.succData(this.apl_applicantService.getAppperAndThiperByApplyid(applyid));
    }

    @Override
    public ResponseDTO getApplicantWithGroup(String applyid) {
        try {
            return ResponseDTO.succData(this.apl_applicantService.getApplicantWithGroup(applyid));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.wrap(500, "查询失败");
        }
    }

    /**
     * 申请人查询-全部查询不分页
     */
    @Override
    public ResponseDTO getApplicantByApplyid(String applyid) {
        try {
            List<Apl_applicant> applicantList = this.apl_applicantService.getApplicantByApplyid(applyid);
            if (CollectionUtil.isNotEmpty(applicantList)) {
                for (Apl_applicant apl_applicant : applicantList) {
                    apl_applicant.geneText();
                }
            }
            return ResponseDTO.succData(applicantList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.wrap(500, "查询失败");
        }
    }

    /**
     *
     * @param name
     * @return
     */
    @Override
    public ResponseDTO searchByName(String name) {
        try {
            List<Apl_applicant> applicantList = this.apl_applicantService.searchByName(name);
            if (CollectionUtil.isNotEmpty(applicantList)) {
                for (Apl_applicant apl_applicant : applicantList) {
                    apl_applicant.geneText();
                }
            }
            return ResponseDTO.succData(applicantList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.wrap(500, "查询失败");
        }
    }

    @Override
    public ResponseDTO getApplicantAndAgent(String applyid) {
        try {
            return ResponseDTO.succData(this.apl_applicantService.getApplicantAndAgent(applyid));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("/getApplicantAndAgent/searchByName 查询申请人关联的代理人列表失败 ->  msg[{}]", e.getMessage());
            return ResponseDTO.wrap(500, "查询申请人关联的代理人列表失败 -> " + e.getMessage());
        }

    }

    @Override
    public ResponseDTO deleteAttachId(String id, Integer type, String attachId) {
        try {
            Assert.notNull(type, "操作类型不能为空");
            Apl_applicant apl_applicant = this.apl_applicantService.getById(id);
            // 删除文件E
            FileController fileController = SpringHolder.getBean(FileController.class);
            fileController.minioRemove(null,attachId);
            switch (type) {
                case 0:
                    String filecardId = apl_applicant.getFilecard();
                    if (!StringUtil.isEmpty(filecardId)) {
                        List<String> restFileIds = Arrays.asList(filecardId.split(",")).stream().filter(item -> !item.equals(attachId)).collect(Collectors.toList());
                        if (CollectionUtil.isEmpty(restFileIds)) {
                            apl_applicant.setFilecard(null);
                        }
                        apl_applicant.setFilecard(String.join(",", restFileIds));
                    }
                    break;
                case 1:
                    String doccardId = apl_applicant.getDoccard();
                    if (!StringUtil.isEmpty(doccardId)) {
                        List<String> restDocIds = Arrays.asList(doccardId.split(",")).stream().filter(item -> !item.equals(attachId)).collect(Collectors.toList());
                        if (CollectionUtil.isEmpty(restDocIds)) {
                            apl_applicant.setDoccard(null);
                        }
                        apl_applicant.setDoccard(String.join(",", restDocIds));
                    }
                    break;
                default:
                    break;
            }
            this.apl_applicantService.saveOrUpdate(apl_applicant);
            return ResponseDTO.succ();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.wrap(500, "删除附件失败");
        }
    }

    @Override
    public ResponseDTO updateAttachId(String id, Integer type, String attachId) {
        try {
            Assert.notNull(type, "操作类型不能为空");
            Apl_applicant apl_applicant = this.apl_applicantService.getById(id);
            switch (type) {
                case 0:
                    apl_applicant.setFilecard(attachId);
                    break;
                case 1:
                    apl_applicant.setDoccard(attachId);
                    break;
                default:
                    break;
            }
            this.apl_applicantService.saveOrUpdate(apl_applicant);
            return ResponseDTO.succ();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.wrap(500, "更新附件id失败");
        }
    }

    @Override
    public ResponseDTO getApplicantAndThirdList(String applyid) {
        // 查询申请人
        List<Apl_applicant> applicationList = this.apl_applicantService.getApplicantByApplyid(applyid);
        // 查询第三人
        List<Apl_thirdper> thirdperList = this.apl_thirdperService.getThirdListByApplyid(applyid);

        Map<String,List> result = new HashMap<String,List>();
        result.put("applicant", applicationList);
        result.put("third", thirdperList);
        return ResponseDTO.succData(result);

    }

    @Override
    public ResponseDTO getCardnoPendingList(Apl_applicantPageInfo pageInfo) {

        return ResponseDTO.succData(this.apl_applicantService.getCardnoPendingList(pageInfo));

    }

    @Override
    public ResponseDTO getCardnoProcessedList(Apl_applicantPageInfo pageInfo) {
        return ResponseDTO.succData(this.apl_applicantService.getCardnoProcessedList(pageInfo));
    }

}
